﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace My.Utils
{
    public class MyHttp
    {

        CookieContainer myCookieContainer = null;
        public MyHttp() {
            myCookieContainer = new CookieContainer();
        }

        public  bool ValidateServerCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }


        public string Get(string url) {
            string result = string.Empty;
            try
            {
                result= RequestUrl(url, "get");
            }
            catch (Exception ex) { }
            return result;
        }

        public string Post(string url, string postData) {
            return RequestUrl(url, postData);
        }


        private string RequestUrl(string url, string postData)
        {
            if (url.StartsWith("https://"))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
            }
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727;)";
            myHttpWebRequest.Accept = "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*";
            myHttpWebRequest.Expect = "";
            //myHttpWebRequest.Headers.Add("Accept-Language", "zh-cn");
            //myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            myHttpWebRequest.Referer = "http://www.google.com/";
            Stream myStream = new MemoryStream();//定义这个Stream是只是为了得到发送字串 经过编码之后得到的byte的长度。
            StreamWriter myStreamWriter = new StreamWriter(myStream, Encoding.Default);//用默认编码 得到Stream
            
            long len;
            try
            {
                myStreamWriter.Write(postData);
                myStreamWriter.Flush();

                len = myStream.Length;//目的完成
            }
            finally
            {
                myStreamWriter.Close();
            }




            if (postData.IndexOf("<?xml") >= 0)
            {
                myHttpWebRequest.Method = "POST";
                myHttpWebRequest.ContentType = "application/xml";
            }
            else if (postData.IndexOf("get") == 0 || postData == string.Empty)
            {
                myHttpWebRequest.Method = "GET";
                myHttpWebRequest.ContentType = "text/html";

            }
            else
            {
                myHttpWebRequest.Method = "POST";
                myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            }


            //myHttpWebRequest.ContentLength = len;//如果字符串中存在中文 使用postData.Length得到长度和编码之后的长度是不一样的:(



            myHttpWebRequest.CookieContainer = myCookieContainer;
            if (myHttpWebRequest.Method == "POST")
            {
                Stream newStream = myHttpWebRequest.GetRequestStream();
                myStreamWriter = new StreamWriter(newStream, Encoding.Default);//编码使用Encoding.Default 换来换去编码方法 还是用它得到的中文不会出现乱码,特别是把request("")得到的值写入sql数据库的时候 真是奇怪^O^


                myStreamWriter.Write(postData);
                myStreamWriter.Close();
            }


            //获取本次的回馈,先创建接收回馈的类HTTPWEBRESPONSE
            string ret = string.Empty;
            HttpWebResponse myHttpWebResponse = null;
            Stream receiveStream = null;
            try
            {
                myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                //创建接收回馈的字节流类
                myHttpWebResponse.Cookies = myCookieContainer.GetCookies(myHttpWebRequest.RequestUri);


                receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流 

                Encoding encode = System.Text.Encoding.Default;
                StreamReader readStream = new StreamReader(receiveStream, encode);
                ret = readStream.ReadToEnd();
                readStream.Close();
            }
            finally
            {
                if (receiveStream != null)
                {
                    receiveStream.Close();
                }
                myHttpWebResponse.Close();

            }
            return ret;




        }

        public System.Collections.Hashtable HeaderTable = new System.Collections.Hashtable();
        public void AddHeader(string key, string val)
        {
            HeaderTable.Add(key, val);
        }


    }
}
